package vip.redme.memory.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import vip.redme.memory.context.UserContext;
import vip.redme.memory.pojo.entity.User;
import vip.redme.memory.repository.UserRepository;
import vip.redme.memory.util.Args;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登陆信息拦截
 *
 * @author HUZHAOYANG
 * @version 1.0
 * @date 2021/4/23 14:31
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    public static final String USER_ID = "userId";
    public static final String TOKEN = "token";
    @Autowired
    private UserRepository userRepository;

    /**
     * 查询用户信息到context中
     *
     * @param request
     * @param response
     * @param handler
     * @return boolean
     * @author HUZHAOYANG
     * @date 2021/4/23 15:14
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader(TOKEN);
        User user = new User();
        user.setUserName("游客");
        user.setToken(token);
        user.setId(1L);
        if (Args.notEmpty(token)) {
            User userDB = userRepository.findByToken(token);
            if (Args.notEmpty(userDB)) {
                user = userDB;
            }
        }
        UserContext.setUserId(user.getId());
        UserContext.setToken(user.getToken());
        UserContext.setUser(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //ThreadLocal 移除缓存，防止泄露
        UserContext.remove();
    }
}
